package servlet;

import dao.ArticleDao;
import dao.LabelDao;
import dao.daoimpl.ArticleDaoImpl;
import dao.daoimpl.LabelDaoImpl;
import bean.Article;
import bean.Label;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


/*发布博客服务器*/
@WebServlet(name = "AddBlogServlet",urlPatterns = "/AddBlogServlet")
public class AddBlogServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        ArrayList<Article> articles=(ArrayList<Article>)request.getSession().getAttribute("userArticles");
        ArrayList<Label> labels=(ArrayList<Label>)request.getSession().getAttribute("userLabels");
        ArticleDao articleDao=new ArticleDaoImpl();
        String content=request.getParameter("addArticleContent");/*获取文章内容*/
        int likingDegree=0;/*初始化文章喜爱度为0*/
        int views=0;/*初始化文章浏览数为0*/
        String title=request.getParameter("addArticleTitle");/*获取文章标题*/
        String time= new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());/*获取当前时间*/
        int commentCount=0;/*初始化文章评论为0*/
        int category=Integer.parseInt(request.getParameter("addArticleCategory"));/*获取文章目录*/
        String user=request.getParameter("addArticleUser");/*获取文章作者*/
        String [] label=request.getParameterValues("addArticleLabels");/*获取多标签数组*/
        ArrayList<Label> labels1=new ArrayList<>();
        for(int i=0;i< label.length;i++){
           for(int j=0;j<labels.size();j++){
               if(label[i].equals(labels.get(j).getContent())){
                   labels1.add(labels.get(i));
               }
           }
        }
        String type=request.getParameter("addArticleType");/*获取文章类型*/
        String subfield=request.getParameter("addArticleSubfield");/*获取文章分栏*/
        int approve=0;/*未过审核*/
        int like=0;/*初始化点赞数*/
        Article article=new Article(content,likingDegree,views,title,time,commentCount,category,user,labels1,type,subfield,approve,like);
        try {
            if(articleDao.addArticle(article)){/*添加博客*/
                System.out.println("用户发布博客成功");
            }else{
                System.out.println("用户发布博客失败");
            }
        }catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }
}
